import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Image, TextInput } from 'react-native';
import type { ImageSourcePropType } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { Alert, TouchableOpacity } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { useNavigation } from '@react-navigation/native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

import CameraScreen from './camera'
// 定义导航参数类型
type RootStackParamList = {
  Main: undefined;
  Camera: { imageUri: string };
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

const Stack = createStackNavigator<RootStackParamList>();

// 定义组件 props 类型
interface FunctionItemProps {
  title: string;
  icon: string;
}

interface BookItemProps {
  title: string;
  image: { uri: string };
}

// 将原来的 App 组件重命名为 MainScreen
function MainScreen() {
  const navigation = useNavigation<NavigationProp>();
  const handleCameraPress = async () => {
    Alert.alert(
      '相机权限',
      '是否允许访问相机？',
      [
        {
          text: '取消',
          style: 'cancel'
        },
        {
          text: '同意',
          onPress: async () => {
            const { status } = await ImagePicker.requestCameraPermissionsAsync();
            if (status === 'granted') {
              try {
                const result = await ImagePicker.launchCameraAsync({
                  mediaTypes: ImagePicker.MediaTypeOptions.Images,
                  allowsEditing: true,
                  aspect: [4, 3],
                  quality: 1,
                });
                
                if (!result.canceled) {
                  console.log(result.assets[0].uri);
                  navigation.navigate('Camera', { imageUri: result.assets[0].uri });
                }
              } catch (error) {
                Alert.alert('错误', '拍照过程中出现错误');
              }
            } else {
              Alert.alert('提示', '未获得相机权限');
            }
          }
        }
      ]
    );
  };

  return (
    <View style={styles.container}>
      {/* 顶部搜索栏 */}
      <View style={styles.header}>
        <View style={styles.searchBar}>
          <Ionicons name="search-outline" size={20} color="#999" />
          <TextInput 
            style={styles.searchInput}
            placeholder="题目、题号、真题名称"
            placeholderTextColor="#999"
          />
        </View>
        <Ionicons name="person-outline" size={20} color="#999" />
        <Ionicons name="chatbubble-outline" size={20} color="#999" />
      </View>

      {/* 拍照搜题区域 */}
      <TouchableOpacity onPress={handleCameraPress}>
        <View style={styles.cameraSection}>
          <Ionicons name="camera" size={80} color="white" />
          <Text style={styles.cameraText}>搜索答疑</Text>
          <Text style={styles.subText}>大学难题，一查就会</Text>
        </View>
      </TouchableOpacity>

      {/* 功能图标区 */}
      <View style={styles.functionGrid}>
        <View style={styles.gridRow}>
          <FunctionItem title="家教搜题" icon="book-outline" />
          <FunctionItem title="家教批改" icon="create-outline" />
          <FunctionItem title="单词查询" icon="text-outline" />
        </View>
        <View style={styles.gridRow}>
          <FunctionItem title="悬浮窗搜题" icon="search-outline" />
          <FunctionItem title="教材答案" icon="document-text-outline" />
          <FunctionItem title="热门资料" icon="star-outline" />
        </View>
      </View>

      {/* 教材列表 */}
      <View style={styles.bookList}>
        <BookItem 
          title="高等数学（第八版）高等教育出版社"
          image={{uri: 'https://img2.doubanio.com/view/subject/l/public/s33644151.jpg'}}
        />
        <BookItem 
          title="全新版大学进阶英语综合教程综合训练3 上海外语教育出版社"
          image={{uri: 'https://img2.doubanio.com/view/subject/l/public/s29959891.jpg'}}
        />
        <BookItem 
          title="高等数学（第八版）高等教育出版社"
          image={{uri: 'https://img2.doubanio.com/view/subject/l/public/s33644151.jpg'}}
        />
        <BookItem 
          title="全新版大学进阶英语综合教程综合训练3 上海外语教育出版社"
          image={{uri: 'https://img2.doubanio.com/view/subject/l/public/s29959891.jpg'}}
        />
      </View>
    </View>
  );
}

// 功能图标组件
const FunctionItem: React.FC<FunctionItemProps> = ({ title, icon }) => (
	<View style={styles.functionItem}>
		<Ionicons name={icon as any} size={24} color="#666" />
		<Text style={styles.functionText}>{title}</Text>
	</View>
);

// 教材项组件
const BookItem: React.FC<BookItemProps> = ({ title, image }) => (
  <View style={styles.bookItem}>
    <Image source={image} style={styles.bookImage} />
    <Text style={styles.bookTitle} numberOfLines={2}>{title}</Text>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    paddingTop: 40,
    paddingHorizontal: 15,
    backgroundColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchBar: {
    flex: 1,
    backgroundColor: '#f0f0f0',
    borderRadius: 20,
    padding: 10,
    marginBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    marginRight: 15,
  },
  searchInput: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
  },
  cameraSection: {
    backgroundColor: '#1E90FF',
    padding: 30,
    alignItems: 'center',
    width: '95%',
    height: 250,
    borderRadius: 15,
    alignSelf: 'center',
    marginTop: 10,
  },
  cameraText: {
    color: 'white',
    fontSize: 24,
    marginTop: 10,
  },
  subText: {
    color: 'white',
    fontSize: 16,
    marginTop: 5,
  },
  functionGrid: {
    backgroundColor: '#fff',
    padding: 20,
    marginTop: 10,
    width: '95%',
    height: 250,
    borderRadius: 15,
    alignSelf: 'center',
  },
  gridRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 30,
    marginTop: 30,
  },
  functionItem: {
    alignItems: 'center',
  },
  functionText: {
    marginTop: 5,
    fontSize: 12,
    color: '#333',
  },
  bookList: {
    backgroundColor: '#fff',
    padding: 15,
    marginTop: 10,
    width: '95%',
    height: 400,
    borderRadius: 15,
    alignSelf: 'center',
  },
  bookItem: {
    flexDirection: 'row',
    marginBottom: 15,
    alignItems: 'center',
  },
  bookImage: {
    width: 60,
    height: 80,
    marginRight: 10,
    borderRadius: 4,
    backgroundColor: '#f0f0f0'
  },
  bookTitle: {
    flex: 1,
    fontSize: 14,
    color: '#333',
  },
});

// 导出组件
export default function HomeScreen() {
  return (
    <View style={styles.container}>
      <Stack.Navigator screenOptions={{ headerShown: false }}>
        <Stack.Screen name="Main" component={MainScreen} />
        <Stack.Screen name="Camera" component={CameraScreen} />
      </Stack.Navigator>
    </View>
  );
} 